import Log from '../utils/log.js'
const log = new Log('ygRocker组件页面')
export default {
  data: {
    x: 0,
    y: 0,
    top: 0,
    left: 0,
    isTouch: false,
    speed: 0.04, // 速度
    xx: 0,
    yy: 0,
    timer: null,
    d_x: 0,
    d_y: 0,
    angle: 0,
  },
  props: {
    rockerData: {
      type: Object,
      default: {
        ou_width: 140,
        ou_height: 140,
        in_width: 60,
        in_height: 60,
      },
    }
  },
  onInit() {
  },
  onShow(){
  },
  ani(t){
    clearInterval(this.timer);
    this.timer = setInterval(()=>{
      if(!this.isTouch){
        clearInterval(this.timer)
      } else {
        this.d_x = this.d_x + this.xx;
        this.d_y = this.d_y + this.yy;
        this.$emit('play', {x: this.d_x, y: this.d_y, angle: this.angle})
        if(this.d_x <= 0){
          this.d_x = 0;
        }
        if(this.d_x >= 680){
          this.d_x = 680;
        }
        if(this.d_y <= 0){
          this.d_y = 0;
        }
        if(this.d_y >= 292){
          this.d_y = 292;
        }
      }
    },t)
  },
  touchStart(e){
    let t = e.touches[0];
    let d = this.$refs.ygRockerItem.getBoundingClientRect();
    this.x = d.left + d.width / 2;
    this.y = d.top + d.height / 2;
    this.isTouch = true;
    this.setSide(t);
    this.ani(10);
//    this.$emit('play', {x: this.d_x, y: this.d_y, angle: this.angle})
  },
  touchMove(e){
    let t = e.touches[0];
    this.setSide(t);
//    this.$emit('play', {x: this.d_x, y: this.d_y, angle: this.angle})
  },
  touchEnd(){
    this.isTouch = false;
    // 回到中心位置
    this.top = 0;
    this.left = 0;
  },
  setFlag(num){
    return num > 0 ? 0 - num : Math.abs(num);
  },
  setSide(t){
    let x = this.x - t.globalX;
    let y = this.y - t.globalY;
    // 获取到当前位置到圆心半径
    let temp = Math.sqrt(Math.pow(x,2) + Math.pow(y,2));
    let r = this.rockerData.ou_width / 2;
    let r2 = temp <= r ? r : temp;
    let top = Math.sin(y/r2) * (this.rockerData.ou_width / 2);
    let left = Math.sin(x/r2) * (this.rockerData.ou_width / 2);
    this.top = this.setFlag(top);
    this.left = this.setFlag(left);
    this.xx = -1 * x * this.speed;
    this.yy = -1 * y * this.speed;
    this.angle = this.getAngle({x: (-1 * x), y});
//    log.debug(`移动 x：${x},y: ${y},角度：${this.getAngle({x: (0 - x), y})}`)
  },
  getAngle(obj){
    let {x, y} = obj;
    //返回角度,不是弧度
    let res = 180 * Math.atan(y / x) / Math.PI;
    if(x > 0 && y > 0){
      res = 90 - Math.abs(res)
    }
    if(x > 0 && y < 0){
      res = 90 + Math.abs(res)
    }
    if(x < 0 && y < 0){
      res = 180 + (90-Math.abs(res))
    }
    if(x < 0 && y > 0){
      res = 270 + Math.abs(res)
    }
    return res === res ? res.toFixed(2) : 0;
  }
}



